package org.edu.zzu.health_report.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.edu.zzu.health_report.domain.User;
import org.edu.zzu.health_report.service.UserService;
import org.edu.zzu.health_report.mapper.UserMapper;
import org.edu.zzu.health_report.util.AesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 高朋
* @description 针对表【user(用户表)】的数据库操作Service实现
* @createDate 2021-11-08 15:30:57
*/
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{


    @Autowired
    private UserMapper userMapper;

    public static String ENCRYPT_KET="key_pwd";


    @Override
    public int saveWithSelective(User user) {
        user.setUserPwd(AesUtil.encrypt(user.getUserPwd(),ENCRYPT_KET));
        return userMapper.insertSelective(user);
    }

    @Override
    public User getByUserId(String userId) {
        User user = userMapper.selectByUserId(userId);
        String userPwd = user.getUserPwd();
        try {
            byte[] decryptPwd = AesUtil.decrypt(Hex.decodeHex(userPwd), ENCRYPT_KET);
            userPwd=new String(decryptPwd,"UTF-8");
            user.setUserPwd(userPwd);

        } catch (DecoderException | UnsupportedEncodingException e) {
            log.error("decrypt failed,userId={},exception={}",userId,e.getMessage());
        }
        return user;
    }

    @Override
    public List<User> getAll() {
        List<User> users = userMapper.selectAll();
        return users.stream().peek(user -> {
            try {
                String userPwd = user.getUserPwd();
                byte[] decryptPwd = AesUtil.decrypt(Hex.decodeHex(userPwd), ENCRYPT_KET);
                userPwd=new String(decryptPwd,"UTF-8");
                user.setUserPwd(userPwd);
            } catch (DecoderException | UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }).collect(Collectors.toList());
    }





    public static void main(String[] args) {


    }



}




